package yue.shen.android.demo.select

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.permissions.RxPermissions
import com.luck.picture.lib.tools.PictureFileUtils
import com.luck.picture.lib.tools.ToastManage
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import yue.shen.android.demo.R
import yue.shen.android.demo.databinding.ActivitySelectPictureCameraBinding

class SelectPicForCameraActivity : AppCompatActivity() {

    private val rxPermissions: RxPermissions by lazy { RxPermissions(this) }

    private var imagePath = ""

    private lateinit var viewBinding: ActivitySelectPictureCameraBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = ActivitySelectPictureCameraBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        initView()
    }

    private fun initView() {
        viewBinding.btnOpenCamera.setOnClickListener {
            openCamera()
        }
    }

    private fun openCamera() {
        rxPermissions.request(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(object : Observer<Boolean> {
            override fun onSubscribe(d: Disposable) {}
            override fun onNext(aBoolean: Boolean) {
                if (aBoolean) {
                    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                    if (intent.resolveActivity(packageManager) != null) {
                        val file = PictureFileUtils.createCameraFile(
                            this@SelectPicForCameraActivity,
                            1,
                            "",
                            ".jpg"
                        )
                        imagePath = file.absolutePath
                        val authority = "$packageName.provider"
                        val imageUri = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            //通过FileProvider创建一个content类型的Uri
                            FileProvider.getUriForFile(
                                this@SelectPicForCameraActivity,
                                authority,
                                file
                            )
                        } else {
                            Uri.fromFile(file)
                        }
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                        this@SelectPicForCameraActivity.startActivityForResult(
                            intent,
                            PictureConfig.REQUEST_CAMERA
                        )
                    }
                } else {
                    ToastManage.s(this@SelectPicForCameraActivity, "被拒绝")
                }
            }

            override fun onError(e: Throwable) {}
            override fun onComplete() {}
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == PictureConfig.REQUEST_CAMERA) {
            CameraPreviewActivity.startActivity(this, imagePath, 101)
        } else if (resultCode == Activity.RESULT_OK && requestCode == 101) {
            val path = data?.getStringExtra("data")
            if (path?.isEmpty() == false) {
                setImagePath(path)
            }
        } else if (resultCode == -2 && requestCode == 101) {
            openCamera()
        }
    }


    private fun setImagePath(path: String) {
        val options: RequestOptions = RequestOptions()
            .placeholder(R.drawable.ic_placeholder)
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
        Glide.with(this)
            .asBitmap()
            .load(path)
            .apply(options)
            .into(object : BitmapImageViewTarget(viewBinding.imageView) {
                override fun setResource(resource: Bitmap?) {
                    val circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(resources, resource)
                    viewBinding.imageView.setImageDrawable(circularBitmapDrawable)
                }
            })
    }
}